import {
  getRouteByKey, ROUTE_CONFIG, ROUTE_KEY, routes,
} from '@/routers/menus';
import { useEffect, useMemo } from 'react';
import { matchPath, useLocation, useNavigate } from 'react-router-dom';

export const useTitle = (title:string) => {
  useEffect(() => {
    document.title = title;
  }, [title]);
};

/**
 * 通过页面跳转器
 */
export const useGoto = () => {
  const navigate = useNavigate();
  const back = () => navigate(-1);
  const go = (propKey?:string, params?:Record<string, string | number>) => {
    if (!propKey) {
      navigate('/');
    }
    const route = getRouteByKey(propKey!);
    if (route && route.path) {
      if (!params) {
        navigate(`/${route.path}`);
      } else {
        // 例子：/page/:id params:{id:1}  将会转化为=>   /page/:1
        const url = route.path.replace(/\/:(\w+)/g, (exp:string, exp1:string) => `/${params[exp1]}`);
        navigate(`/${url}`);
      }
    }
  };
  return { back, go };
};

/**
 * 获取当前页面的url匹配的路由
 */
export const useMatchedRoute = () => {
  const r = useLocation();
  const route = useMemo(() => routes.find(
    (item) => matchPath(`/${item.path}`, r.pathname),
  ), [r.pathname]);
  return route;
};

// 判断当前是否是门店页面
export const useIsOrgRoute = () => {
  const curRoute = useMatchedRoute();
  if (curRoute?.path === ROUTE_CONFIG[ROUTE_KEY.ORG].path) {
    return true;
  }
  return false;
};
